package co.edu.usbcali.unidades.dataaccess.dao;

import co.edu.usbcali.unidades.dataaccess.sessionFactory.HibernateSessionFactory;
import co.edu.usbcali.unidades.modelo.Ciudad;
import co.edu.usbcali.unidades.modelo.ZonaComun;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;

import org.hibernate.criterion.Example;

import java.math.BigDecimal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * A data access object (DAO) providing persistence and search support for
 * ZonaComun entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 *
 *
 * @author Zathura Code Generator http://code.google.com/p/zathura
 *
 */
public class ZonaComunDAO implements IZonaComunDAO {
    private static final Log log = LogFactory.getLog(ZonaComunDAO.class);

    // property constants
    //public static final String  ZOCCODIGO = "zocCodigo";
    public static final String ZOCCODIGO = "zocCodigo";

    //public static final String  ZOCNOMBRE = "zocNombre";
    public static final String ZOCNOMBRE = "zocNombre";

    //public static final Long  ZOCVALOR = "zocValor";
    public static final String ZOCVALOR = "zocValor";

    private Session getSession() {
        return HibernateSessionFactory.getSession();
    }

    /**
    *
    * @param Instance
    *            ZonaComun Instance to persist
    * @throws RuntimeException
    *             when the operation fails
    */
    public void save(ZonaComun instance) {
        log.debug("saving ZonaComun instance");

        try {
            getSession().save(instance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    /**
    * @param Instance
    *            ZonaComun Instance to delete
    * @throws RuntimeException
    *             when the operation fails
    */
    public void delete(ZonaComun instance) {
        log.debug("deleting ZonaComun instance");

        try {
            getSession().delete(instance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    /**
    *
    * @param Instance
    *            ZonaComun Instance to update
    * @throws RuntimeException
    *             when the operation fails
    */
    public void update(ZonaComun instance) {
        log.debug("updating ZonaComun instance");

        try {
            getSession().update(instance);
            log.debug("update successful");
        } catch (RuntimeException re) {
            log.error("update failed", re);
            throw re;
        }
    }

    public ZonaComun findById(String id) {
        log.debug("finding ZonaComun instance with id: " + id);

        try {
            ZonaComun instance = (ZonaComun) getSession()
                                                 .get(ZonaComun.class, id);

            return instance;
        } catch (RuntimeException re) {
            log.error("finding ZonaComun failed", re);
            throw re;
        }
    }

    public List<ZonaComun> findByExample(ZonaComun instance) {
        log.debug("finding ZonaComun instance by example");

        try {
            List results = getSession().createCriteria("ZonaComun")
                               .add(Example.create(instance)).list();
            log.debug("find by example successful, result size: " +
                results.size());

            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    /**
    * Find all  ZonaComun entities with a specific property value.
    *
    * @param value
    *            the property value to match
    * @param propertyName
    *            the property to search in the instance
    * @return List< ZonaComun> found by query
        */
    public List<ZonaComun> findByProperty(String propertyName, Object value) {
        log.debug("finding ZonaComun instance with property: " + propertyName +
            ", value: " + value);

        try {
            String queryString = "from ZonaComun as model where model." +
                propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        }
    }

    public List<ZonaComun> findByZocCodigo(Object zocCodigo) {
        return findByProperty(ZOCCODIGO, zocCodigo);
    }

    public List<ZonaComun> findByZocNombre(Object zocNombre) {
        return findByProperty(ZOCNOMBRE, zocNombre);
    }

    public List<ZonaComun> findByZocValor(Object zocValor) {
        return findByProperty(ZOCVALOR, zocValor);
    }

    /**
    * Find all ZonaComun entities.
    *
    * @return List<ZonaComun> all ZonaComun instances
    */
    public List<ZonaComun> findAll() {
        log.debug("finding all ZonaComun instances");

        try {
            String queryString = "from ZonaComun";
            Query queryObject = getSession().createQuery(queryString);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public List<ZonaComun> findByCriteria(String whereCondition) {
        log.debug("finding ZonaComun " + whereCondition);

        try {
            String where = ((whereCondition == null) ||
                (whereCondition.length() == 0)) ? "" : ("where " +
                whereCondition);
            final String queryString = "select model from ZonaComun model " +
                where;
            Query query = getSession().createQuery(queryString);
            List<ZonaComun> entitiesList = query.list();

            return entitiesList;
        } catch (RuntimeException re) {
            log.error("find By Criteria in ZonaComun failed", re);
            throw re;
        }
    }

    public List<ZonaComun> findPageZonaComun(String sortColumnName,
        boolean sortAscending, int startRow, int maxResults, String nombreUni) {
        log.debug("finding ZonaComun findPageZonaComun");

        if ((sortColumnName != null) && (sortColumnName.length() > 0)) {
            try {
                String queryString = "select model from ZonaComun model where model.unidadResidencial.unrNombre:=nombre order by model." +
                    sortColumnName + " " + (sortAscending ? "asc" : "desc");
                
                Query queryObject=getSession().createQuery(queryString);
				queryObject.setParameter("nombre", nombreUni);
				
				return queryObject.setFirstResult(startRow).setMaxResults(maxResults).list();

                /*return getSession().createQuery(queryString)
                           .setFirstResult(startRow).setMaxResults(maxResults)
                           .list();*/
            } catch (RuntimeException re) {
                throw re;
            }
        } else {
            try {
                String queryString = "select model from ZonaComun model where model.unidadResidencial.unrNombre=:nombre";

                Query queryObject=getSession().createQuery(queryString);
				queryObject.setParameter("nombre", nombreUni);
				
				return queryObject.setFirstResult(startRow).setMaxResults(maxResults).list();
                
                /*return getSession().createQuery(queryString)
                           .setFirstResult(startRow).setMaxResults(maxResults)
                           .list();*/
            } catch (RuntimeException re) {
                throw re;
            }
        }
    }

    public Long findTotalNumberZonaComun(String nombreUni) {
        log.debug("finding ZonaComun count");

        try {
            String queryString = "select count(*) from ZonaComun model where model.unidadResidencial.unrNombre=:nombre";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter("nombre", nombreUni);

            return (Long) queryObject.list().get(0);
        } catch (RuntimeException re) {
            throw re;
        }
    }
    
    public ZonaComun getZonaComunUnidad(String zcNombre, String unrNit) {
    	List<ZonaComun> zonaC = new ArrayList<ZonaComun>();
        try {
        	Query q = HibernateSessionFactory.getSession().createQuery("select zc from ZonaComun zc where zc.zocNombre=:nombre and zc.unidadResidencial.unrNit=:nombre2");
        	q.setParameter("nombre", zcNombre);
        	q.setParameter("nombre2", unrNit);
        	zonaC=q.list();
        	if(zonaC.size()== 0){
        		return null;
        	}        	
            return zonaC.get(0);            
        } catch (RuntimeException re) {
            log.error("finding ZonaComun failed", re);
            throw re;
        }
    }
}
